#include "userconnection.h"

#include <boost/bind.hpp>
#include <boost/thread.hpp>


UserConnection::UserConnection(
    boost::asio::io_service * io, UserConnectionManager * mgr, const std::string& address)
    : 
      LoggingService("CONNECTION"),
      m_authorized(false),
      m_ip_address(address),
      m_mgr(mgr),
      m_socket_from(),
      m_socket_to()
{
  

}


bool UserConnection::isAuthorized()
{
  return m_authorized;
}

bool UserConnection::isSetup()
{
  return m_socket_from.get() != 0 && m_socket_to.get() != 0;
}


const std::string& UserConnection::getIpAddress()
{
  return m_ip_address;
}

void UserConnection::updateUserSocketFrom(const boost::shared_ptr<tcp::socket>& socket)
{
  if (m_socket_from.get() == 0)
  {
    m_socket_from = socket;
  }
  else
  {
    m_socket_from.get()->cancel();
    m_socket_from.get()->close();
    m_socket_from = socket;
  }

//  listen_command_from();
}

void UserConnection::updateUserSocketTo(const boost::shared_ptr<tcp::socket>& socket)
{
  if (m_socket_to.get() == 0)
  {
    m_socket_to = socket;
  }
  else
  {
    m_socket_to.get()->cancel();
    m_socket_to.get()->close();
    m_socket_to = socket;
  }
}

std::string UserConnection::toString()
{
  char s[256];

  if (m_authorized)
  {
    sprintf(s, "(authorized, %s, %i, %i)", m_ip_address.c_str(), m_socket_from.get() != 0, m_socket_to.get() != 0);

  }
  else
  {
    sprintf(s, "(unauthorized, %s, %i, %i)", m_ip_address.c_str(), m_socket_from.get() != 0, m_socket_to.get() != 0);
  }
  
  return std::string(s);

}

boost::shared_ptr<tcp::socket>& UserConnection::getUserSocketFrom()
{ 
  return m_socket_from;
}

boost::shared_ptr<tcp::socket>& UserConnection::getUserSocketTo()
{ 
  return m_socket_to;
}


void UserConnection::listen_command_from()
{
  debug() << "server listen to connections from client." << endl;
    boost::asio::async_read(
        *m_socket_from.get(), 
        boost::asio::buffer(m_buffer, COMMAND_LENGTH), 
        boost::bind(&UserConnection::handle_read_command_from, 
          this, boost::asio::placeholders::error)
        );  
}
void UserConnection::handle_read_command_from(const boost::system::error_code& err)
{
  debug() << "handle read command!"  <<endl;

  if (!err)
  {
    info() << "command: " << m_buffer << endl;
  }
  else
  {
    error() << "error reading command to server: " << err;
  }

  boost::this_thread::yield();

  listen_command_from();
}






